<template>
	<BasicModal @register="registerModalInner" :title="getTitle" @ok="handleSubmit" destroyOnClose>
		<BasicForm @register="registerForm"></BasicForm>
	</BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, BasicForm } from '#/components';
import { useForm } from '#/hooks';
import { useModalInner } from '#/Modal';
import type { FormSchema } from '#/types';
import { addOrEditDept, getDeptTree } from '@/api/sys/dept';
import { useMessage } from '@/hooks/web/useMessage';
import { computed, ref, unref } from 'vue';

const formSchema: FormSchema[] = [
	{
		field: 'deptName',
		label: '部门名称',
		component: 'Input',
		required: true,
	},
	{
		field: 'parentId',
		label: '上级部门',
		component: 'ApiTreeSelect',
		required: true,
		componentProps: {
			api: getDeptTree,
			fieldNames: { key: 'id', value: 'deptId', label: 'deptName' },
			afterFetch: data => {
				let tree = [{ deptId: 0, deptName: '组织架构', children: null }, ...data];
				return tree;
			},
		},
	},
	{
		field: 'status',
		label: '状态',
		component: 'RadioButtonGroup',
		defaultValue: true,
		componentProps: {
			options: [
				{ label: '启用', value: true },
				{ label: '停用', value: false },
			],
		},
		required: true,
	},
	{
		field: 'remark',
		label: '备注',
		component: 'InputTextArea',
	},
];

const isUpdate = ref(true);
const deptId = ref();

const { createMessage } = useMessage();

const [registerModalInner, { closeModal }] = useModalInner(data => {
	resetFields();
	isUpdate.value = !!data?.isUpdate;
	console.log('000000000000000000000000', data);

	if (unref(isUpdate)) {
		deptId.value = data.record.deptId;
		setFieldsValue({ ...data.record });
	}
});

const [registerForm, { setFieldsValue, validate, resetFields }] = useForm({
	labelWidth: 100,
	schemas: formSchema,
	showActionButtonGroup: false,
	baseRowStyle: {
		'justify-content': 'space-around',
	},
	baseColProps: {
		span: 20,
	},
});

const getTitle = computed(() => (unref(isUpdate) ? '编辑部门' : '新增部门'));

const emit = defineEmits(['success', 'register']);
async function handleSubmit() {
	try {
		const values = await validate();
		unref(isUpdate) && (values.deptId = deptId.value);
		await addOrEditDept(isUpdate.value, values);
		closeModal();
		emit('success');
	} catch (_err) {
		createMessage.error('操作失败');
	}
}
</script>
<style lang="less" scoped></style>
